package com.infore.airsupervise.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.StationExpandAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.bean.BaseBean;
import com.infore.airsupervise.bean.EventDetailsE;
import com.infore.airsupervise.bean.EventE;
import com.infore.airsupervise.bean.StationExpandE;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.impl.EventBizImpl;
import com.infore.airsupervise.biz.impl.UserAndGridBizImpl;
import com.infore.airsupervise.http.BaseResponse;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.fragment.PsonSelectorFragment;
import com.infore.airsupervise.ui.fragment.StationTreeFragment;
import com.infore.airsupervise.utils.DateUtil;
import com.infore.airsupervise.utils.DialogUtil;
import com.infore.airsupervise.utils.ImageUtil;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by Administrator on 2017/8/22.
 */

public class EventEditorActivity extends BaseActivity {

    @BindView(R.id.titlebar_left_menu)
    AwesomeTextView titlebarLeftMenu;
    @BindView(R.id.titlebar_title)
    TextView titlebarTitle;
    @BindView(R.id.titlebar_right_menu)
    AwesomeTextView titlebarRightMenu;

    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;

    @BindView(R.id.editor_item_event_name)
    LinearLayout mEditorItemEvenName;
    @BindView(R.id.editor_event_name)
    EditText mEditorEventName;

    @BindView(R.id.editor_item_station_name)
    LinearLayout mEditorItemStationName;
    @BindView(R.id.editor_station_name)
    TextView mEditorStationName;

    @BindView(R.id.editor_item_eventhappen_time)
    LinearLayout mEditorItemEventHappenTime;
    @BindView(R.id.editor_eventhappen_time)
    TextView mEditorEventHappenTime;

    @BindView(R.id.editor_item_event_pollutionfactor)
    LinearLayout mEditorItemEventPollutionFactor;
    @BindView(R.id.editor_event_pollutionfactor)
    TextView mEditorEventPollutionFactor;



    @BindView(R.id.editor_item_event_urgency)
    LinearLayout mEditorItemEventUrgency;
    @BindView(R.id.editor_event_urgency)
    TextView mEditorEventUrgency;

    @BindView(R.id.editor_item_event_createperson)
    LinearLayout mEditorItemEventCreatePerson;
    @BindView(R.id.editor_task_createperson)
    TextView mEditorEventCreatePerson;

    @BindView(R.id.editor_item_event_handlerperson)
    LinearLayout mEditorItemEventHandlerPerson;
    @BindView(R.id.editor_event_handlerperson)
    TextView mEditorEventHandlerPerson;

    @BindView(R.id.editor_event_textdesc)
    EditText mEditorEventDesc;

    @BindView(R.id.submit_event_data)
    Button mSubmitEventData;

    @BindView(R.id.rest_event_data)
    Button mRestEventData;
    @BindView(R.id.event_base_title)
    TextView mBaseTitle;

    private boolean[] timeType = {true,true,true,true ,true ,true};

    private EventE bean;
    private SweetAlertDialog dialog;
    private EventBizImpl eventBiz;
    private String eventid;
    private StationTreeFragment drawFragment;
    private OptionsPickerView pvOptions;
    private TimePickerView timePickerView;
    private String time;
    private OptionsPickerView factorPickerView;

    private List<String> factorList = null;
    private List<String> pollutionlevel = null;
    private OptionsPickerView pollutionLevelPickerView;
    private OptionsPickerView eventUrgencyPickerView;
    private UserAndGridBizImpl allPersonBiz;
    private List<String> persons=new ArrayList<>();//派遣人的名称
    private List<String> personsid=new ArrayList<>();//派遣人id集合
    private OptionsPickerView handlerPersonPickerView;
    private int editor;
    private String stationMn;//站点编号
    private String personid;//派遣人id
    private int pollulevel=-1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_editor);
        ButterKnife.bind(this);
        eventid = getIntent().getStringExtra("eventid");//编辑事件
        editor = getIntent().getIntExtra("editor",0);
        eventBiz = new EventBizImpl();
        allPersonBiz = new UserAndGridBizImpl();
        mBaseTitle.setText("基本信息");
        //编辑事件
        if(editor ==1){
            LoadEventDetails();
            titlebarTitle.setText("编辑事件");

            //mBaseTitle.setText("处理信息");
        //    requestStation();
        }else if(editor ==2){  //新建事件
            titlebarTitle.setText("新建事件");

//            mEditorEventName.setText("   ");
//            mEditorEventName.setSelection(mEditorEventName.getText().length());
            mEditorEventCreatePerson.setText(UserE.getUserInfo().getRealName());
        }

        HandlerEventPerson();
        initView();
        initTimePicker();
        initFactorPicker();
        //initPollutionLevel();
        initEventUrgency();

    }


    public void initView(){
        titlebarLeftMenu.setFontAwesomeIcon(FontAwesome.FA_CHEVRON_LEFT);
        titlebarRightMenu.setVisibility(View.INVISIBLE);
        factorList=new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.airType2)));
        pollutionlevel=new  ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.pollutionlevel)));



    }
    private void LoadEventDetails(){

        dialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText(MsgConst.PLEASE_WAITING);
        dialog.setCancelable(false);
        dialog.show();
        eventBiz.getEventDetails(eventid, new OnServerResponseListener<EventDetailsE>() {
            @Override
            public void onSucceed(EventDetailsE result, String desc) {
               // Log.e("EventDetailsE", result.toString());
             //   titlebarTitle.setText(result.getEventName());
                mEditorEventName.setText(result.getEventName());
                mEditorStationName.setText(result.getStationName());
                mEditorEventHappenTime.setText(result.getEventTime());
                mEditorEventPollutionFactor.setText(result.getFactor());
                //mEditorEventPollutionLevel.setText(result.getEm_degree());
                mEditorEventUrgency.setText(result.getPoll_degree());
                mEditorEventHandlerPerson.setText(result.getDispatcher());
                mEditorEventDesc.setText(result.getDescriptions());
                mEditorEventName.setSelection(result.getEventName().length());//将光标移至文字末尾
                mEditorEventCreatePerson.setText(result.getReporter());
                personid=result.getDispatcherId();
                pollulevel=Integer.valueOf(result.getPoll_level());
                stationMn=result.getMn();
                dialog.dismiss();

            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                dialog.setTitleText(title)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.WARNING_TYPE);
            }
        });

    }





    @OnClick({R.id.editor_item_event_name, R.id.editor_item_station_name,R.id.editor_item_eventhappen_time,
            R.id.editor_item_event_pollutionfactor,R.id.editor_item_event_urgency,
            R.id.editor_item_event_createperson,R.id.editor_item_event_handlerperson})
    void editorEventItem(View view) {
                switch (view.getId()) {
//            case R.id.editor_item_event_name:
//
//                break;
            case R.id.editor_item_station_name:
                if(drawFragment == null){
                    drawFragment = new StationTreeFragment();
                    drawFragment.setCurType(StationExpandAdapter.RB_SELECTE);
                    drawFragment.setOnClickListener(onClicklistener);
                    getSupportFragmentManager().beginTransaction().replace(R.id.drawer_container, drawFragment).commit();
                }
                drawerLayout();
                break;
            case R.id.editor_item_eventhappen_time:
                timePickerView.show();
                break;
            case R.id.editor_item_event_pollutionfactor:
                factorPickerView.show();
                break;
            case R.id.editor_item_event_urgency:
                eventUrgencyPickerView.show();
                break;
            case R.id.editor_item_event_createperson:
                break;
            case R.id.editor_item_event_handlerperson:
                handlerPersonPickerView.show();
                break;
        }

    }

    private void initTimePicker(){
        Calendar endSelectedDate = Calendar.getInstance();
        timePickerView = new TimePickerView.Builder(ctx, timeSelectListener)
                .setTitleText("")
                .setLabel("年", "月", "日", "点", "分", "秒")
                .setType(timeType)
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(18)
                .setRangDate(null , endSelectedDate)
                .setDate(endSelectedDate)
                .setDecorView(null)
                .setTitleText("时间选择")
                .build();
    }

    /**
     * 时间选择回调
     */
    private TimePickerView.OnTimeSelectListener timeSelectListener = new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            time = DateUtil.getStringByFormat(date,DateUtil.FORMAT_DATE_TIME);
            mEditorEventHappenTime.setText(time);
        }
    };



    private void initFactorPicker(){
        factorPickerView = new OptionsPickerView.Builder(ctx , factorSelectListener)
                .isCenterLabel(false)
                .setTitleText("因子")
                .setDividerColor(Color.DKGRAY)
                .setDecorView(null)
                .build();
        factorPickerView.setPicker(factorList);
    }

    /**
     * 因子选择回调
     */
    private OptionsPickerView.OnOptionsSelectListener factorSelectListener = new OptionsPickerView.OnOptionsSelectListener() {
        @Override
        public void onOptionsSelect(int options1, int options2, int options3, View v) {
            mEditorEventPollutionFactor.setText(factorList.get(options1));
        }
    };

//    private void initPollutionLevel(){
//        pollutionLevelPickerView = new OptionsPickerView.Builder(ctx , pollutionLevelListener)
//                .isCenterLabel(false)
//                .setTitleText("污染等级")
//                .setDividerColor(Color.DKGRAY)
//                .setDecorView(null)
//                .build();
//        pollutionLevelPickerView.setPicker(pollutionlevel);
//    }
//
//    private OptionsPickerView.OnOptionsSelectListener pollutionLevelListener = new OptionsPickerView.OnOptionsSelectListener() {
//        @Override
//        public void onOptionsSelect(int options1, int options2, int options3, View v) {
//            mEditorEventPollutionLevel.setText(pollutionlevel.get(options1));
//            pollulevel= options1+1;
//
//        }
//    };

    private void initEventUrgency(){
        eventUrgencyPickerView = new OptionsPickerView.Builder(ctx , eventUrgencyListener)
                .isCenterLabel(false)
                .setTitleText("紧急程度")
                .setDividerColor(Color.DKGRAY)
                .setDecorView(null)
                .build();
        eventUrgencyPickerView.setPicker(pollutionlevel);
    }

    private OptionsPickerView.OnOptionsSelectListener eventUrgencyListener = new OptionsPickerView.OnOptionsSelectListener() {
        @Override
        public void onOptionsSelect(int options1, int options2, int options3, View v) {
            mEditorEventUrgency.setText(pollutionlevel.get(options1));
            pollulevel=options1+1;
        }
    };

    private void HandlerEventPerson(){


        allPersonBiz.getAllPsonRequest(UserE.getUserInfo().getUserId(),
                new OnServerResponseListener<List<UserE>>() {
                    @Override
                    public void onSucceed(List<UserE> result, String desc) {
                      //  dialog.dismiss();
                        UserE.saveAllPson(result);//保存本地
                       // persons=result;
                        for (int i=0;i<result.size();i++){
                            persons.add(result.get(i).getRealName());
                            personsid.add(result.get(i).getUserId());
                        }
                        initPersonPicker(persons);
                    }
                    @Override
                    public void onFailed(int errorCode, String title, String desc) {
                    }
                });
    }

    private void initPersonPicker(List<String> result){
        if(result==null){
            ToastUtil.showLong(this,"没有相关处理人信息");
            return;
        }
        handlerPersonPickerView = new OptionsPickerView.Builder(ctx , personListener)
                .isCenterLabel(false)
                .setTitleText("处理人")
                .setDividerColor(Color.DKGRAY)
                .setDecorView(null)
                .build();
        handlerPersonPickerView.setPicker(result);
    }

    private OptionsPickerView.OnOptionsSelectListener personListener = new OptionsPickerView.OnOptionsSelectListener() {
        @Override
        public void onOptionsSelect(int options1, int options2, int options3, View v) {
            mEditorEventHandlerPerson.setText(persons.get(options1));
            personid=personsid.get(options1);

        }
    };


    /**站点树点击事件
     *
     */
    private StationTreeFragment.OnClickListener onClicklistener = new StationTreeFragment.OnClickListener() {
        @Override
        public void onConfirmClick(String mn) {

        }

        @Override
        public void onConfirmClick(String mn, String name) {
            Log.d("onConfirmClick",mn+"--"+name);
            mEditorStationName.setText(name);
            stationMn=mn;
            drawerLayout();
        }

        @Override
        public void onCancelClick() {
            drawerLayout();
        }
    };

    /**
     * 控制抽屉开关
     */
    private void drawerLayout(){
        if (!drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.openDrawer(Gravity.LEFT);
        } else {
            drawerLayout.closeDrawers();
        }
    }


    /**
     * 提交事件数据
     */
    @OnClick(R.id.submit_event_data)
    void submitEventDataOnclick() {
        if(editor==1){
            //编辑事件
            editorEventData();
        }else if(editor==2){
            //新建事件
            commitEventData();
        }
    }
    @OnClick(R.id.rest_event_data)
    void restEventDataOnclick() {
        mEditorEventName.setText("");
        mEditorStationName.setText("");
        mEditorEventHappenTime.setText("");
        mEditorEventPollutionFactor.setText("");

        mEditorEventUrgency.setText("");
        mEditorEventHandlerPerson.setText("");
        mEditorEventDesc.setText("");
        personid="";
        stationMn="";

    }




    private void editorEventData() {
        // 内容非空判断

        if(TextUtils.isEmpty(mEditorEventName.getText().toString().trim()) ||
                TextUtils.isEmpty(mEditorStationName.getText().toString().trim()) ||
                TextUtils.isEmpty(mEditorEventHappenTime.getText().toString().trim())||
                TextUtils.isEmpty(mEditorEventPollutionFactor.getText().toString().trim())||
                TextUtils.isEmpty(mEditorEventUrgency.getText().toString().trim())||
                TextUtils.isEmpty(mEditorEventCreatePerson.getText().toString().trim()) ||
                TextUtils.isEmpty(mEditorEventHandlerPerson.getText().toString().trim())||
                TextUtils.isEmpty(mEditorEventDesc.getText().toString().trim())){
            ToastUtil.showLong(ctx, "请把信息填写完整");
            return;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("recordTitle",mEditorEventName.getText());
        param.put("mn", stationMn);
        param.put("happenTime", mEditorEventHappenTime.getText());
        param.put("factor", mEditorEventPollutionFactor.getText());
        param.put("dispatcher",personid);
        param.put("describ",mEditorEventDesc.getText());
        param.put("recordId",eventid);
        param.put("dangerLevel",pollulevel);
      //  Log.e("param",UserE.getUserInfo().getUserId()+"--"+mEditorEventName.getText()+"--"+stationMn+"--"+mEditorEventHappenTime.getText()+"--"+mEditorEventPollutionFactor.getText()+"--"+personid+"--"+mEditorEventDesc.getText()+"--");
//
// final SweetAlertDialog dialog =
//                DialogUtil.getInstance().alertProgress(ctx, MsgConst.CONFIRM, true);
        dialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText(MsgConst.PLEASE_WAITING);
        dialog.setCancelable(false);
        dialog.show();
        eventBiz.submitEditorEventData(param, new OnServerResponseListener<BaseResponse>() {
            @Override
            public void onSucceed(BaseResponse result, String desc) {
                //Log.d("BaseResponse",result.getMessage()+"--"+result.getStatus());
                dialog.setTitleText(MsgConst.OPERATION_SUCCESS)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                dialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        forResultFinish();
                        dialog.dismiss();
                    }
                });
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                dialog.setTitleText(title)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.WARNING_TYPE);
            }
        });


    }


    private void commitEventData() {
        // 定位判断

        // 内容非空判断

        if(TextUtils.isEmpty(mEditorEventName.getText().toString().trim()) ||
                TextUtils.isEmpty(mEditorStationName.getText().toString().trim()) ||
                TextUtils.isEmpty(mEditorEventHappenTime.getText().toString().trim())||
                TextUtils.isEmpty(mEditorEventPollutionFactor.getText().toString().trim())||
                TextUtils.isEmpty(mEditorEventUrgency.getText().toString().trim())||
                TextUtils.isEmpty(mEditorEventCreatePerson.getText().toString().trim()) ||
                TextUtils.isEmpty(mEditorEventHandlerPerson.getText().toString().trim())||
                TextUtils.isEmpty(mEditorEventDesc.getText().toString().trim())){
            ToastUtil.showLong(ctx, "请把信息填写完整");
            return;
        }

        dialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText(MsgConst.PLEASE_WAITING);
        dialog.setCancelable(false);
        dialog.show();
        Map<String, Object> param = new HashMap<>();
        param.put("recordTitle",mEditorEventName.getText());
        param.put("mn", stationMn);
        param.put("happenTime", mEditorEventHappenTime.getText());
        param.put("factor", mEditorEventPollutionFactor.getText());
        param.put("dispatcher",personid);
        param.put("describ",mEditorEventDesc.getText());
        param.put("dangerLevel",pollulevel);
        Log.e("param",UserE.getUserInfo().getUserId()+"--"+mEditorEventName.getText()+"--"+stationMn+"--"+mEditorEventHappenTime.getText()+"--"+mEditorEventPollutionFactor.getText()+"--"+personid+"--"+mEditorEventDesc.getText());


        // 发起请求
        eventBiz.submitCreateEventData(param, new OnServerResponseListener<BaseResponse>() {
            @Override
            public void onSucceed(BaseResponse result, String desc) {
               // Log.d("BaseResponse",result.getMessage()+"--"+result.getStatus());
                dialog.setTitleText(MsgConst.OPERATION_SUCCESS)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                dialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        forResultFinish();
                        dialog.dismiss();
                    }
                });
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                dialog.setTitleText(title)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.WARNING_TYPE);
            }
        });
    }


    /**
     * 返回上个界面
     */
    @OnClick(R.id.titlebar_left_menu)
    void leftMenuClick() {
        finish();
    }


    /**
     * 带参数的返回
     */
    private void forResultFinish(){
        setResult(RESULT_OK);
        finish();
    }
}
